import { useState } from 'react';
// 样式文件
import './index.css';

const GoodsManage = () => {
  // 状态管理
  const [fileContent, setFileContent] = useState('');
  const [error, setError] = useState('');
  const [searchTerm, setSearchTerm] = useState('');

  // 处理文件选择
  const handleFileSelect = async (e) => {
    const file = e.target.files?.[0];
    setError('');
    setFileContent('');

    if (!file) return;

    try {
      // 文件验证
      if (!validateFile(file)) return;

      // 读取文件内容
      const content = await readFileContent(file);
      setFileContent(content);
    } catch (err) {
      setError('文件读取失败，请重试');
    }
  };

  // 文件验证
  const validateFile = (file) => {
    const validTypes = ['text/plain', 'application/octet-stream'];
    const validExtensions = ['.txt'];
    const maxSizeMB = 5;

    // 类型验证
    if (
      !validTypes.includes(file.type) &&
      !validExtensions.some(ext => file.name.endsWith(ext))
    ) {
      setError('仅支持.txt文本文件');
      return false;
    }

    // 大小验证
    if (file.size > maxSizeMB * 1024 * 1024) {
      setError(`文件大小不能超过${maxSizeMB}MB`);
      return false;
    }

    return true;
  };

  // 异步读取文件内容
  const readFileContent = (file) => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      
      reader.onload = (event) => {
        resolve(event.target?.result);
      };

      reader.onerror = () => {
        reject(new Error('文件读取失败'));
      };

      reader.readAsText(file, 'UTF-8');
    });
  };

  // 处理内容复制
  const copyToClipboard = async () => {
    try {
      await navigator.clipboard.writeText(fileContent);
      alert('内容已复制到剪贴板');
    } catch (err) {
      alert('复制失败，请手动选择内容复制');
    }
  };

  // 带高亮的文本内容
  const highlightedContent = fileContent
    .split('\n')
    .map((line, lineNum) => ({
      line: lineNum + 1,
      content: searchTerm 
        ? line.split(searchTerm).map((part, i) => (
            <span key={i}>
              {part}
              {i < line.split(searchTerm).length - 1 && (
                <mark>{searchTerm}</mark>
              )}
            </span>
          ))
        : line
    }));

  return (
    <div className="container">
      {/* 文件上传区域 */}
      <div className="upload-area">
        <input
          type="file"
          id="fileInput"
          accept=".txt,text/plain"
          onChange={handleFileSelect}
        />
        <label htmlFor="fileInput">
          <div className="upload-box">
            <div>📁</div>
            <p>点击选择文件或拖拽到此区域</p>
            <small>支持.txt文件，最大5MB</small>
          </div>
        </label>
      </div>

      {/* 错误提示 */}
      {error && <div className="error-alert">⚠️ {error}</div>}

      {/* 内容展示区域 */}
      {fileContent && (
        <div className="content-wrapper">
          {/* 工具栏 */}
          <div className="toolbar">
            <input
              type="text"
              placeholder="搜索内容..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
            />
            <button onClick={copyToClipboard}>复制全部</button>
          </div>

          {/* 带行号的内容 */}
          <div className="content-area">
            {/* 行号列 */}
            <div className="line-numbers">
              {highlightedContent.map(({ line }) => (
                <div key={line}>{line}</div>
              ))}
            </div>

            {/* 内容主体 */}
            <pre className="text-content">
              {highlightedContent.map(({ line, content }) => (
                <div key={line} className="line">
                  {content}
                </div>
              ))}
            </pre>
          </div>
        </div>
      )}
    </div>
  );
};

export default GoodsManage;